#include "PluginWebAfx.h"
#include "MainUIRunner.h"

class ClosureTask : public CefTask 
{
public:
	explicit ClosureTask(const base::Closure& closure): closure_(closure) {}
	virtual void Execute() OVERRIDE {closure_.Run();closure_.Reset();}
private:
	base::Closure closure_;
	IMPLEMENT_REFCOUNTING(ClosureTask);
	DISALLOW_COPY_AND_ASSIGN(ClosureTask);
};

MainUIRunner::MainUIRunner(): m_MsgId(WM_USER + 2767)
{
	Run();
}

MainUIRunner::~MainUIRunner()
{
	DMAutoLock autolock(&m_Lock);
	if (IsWindow())
	{
		DestroyWindow();
	}
}

void MainUIRunner::PostTask(CefRefPtr<CefTask> task)
{
	DMAutoLock autolock(&m_Lock);
	if (task.get())
	{
		if (IsWindow())
		{
			task->AddRef();
			this->PostMessage(m_MsgId,(WPARAM)task.get(),0);
		}
	}
}

void MainUIRunner::PostTask(const base::Closure& closure)
{
	PostTask(new ClosureTask(closure));
}

bool MainUIRunner::RunTaskOnMainUI() const
{
	return m_dwThreadId == ::GetCurrentThreadId();
}

bool MainUIRunner::Run()
{
	ATOM Atom = g_pDMApp->GetClassAtom();
	DMCWnd::CreateWindowEx((LPCWSTR)Atom,NULL,0,0,0,0,1,1,HWND_MESSAGE,0);
	m_dwThreadId = ::GetCurrentThreadId();
	return NULL != m_hWnd;
}

LRESULT MainUIRunner::OnHandlerEvent(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	CefRefPtr<CefTask> task =  reinterpret_cast<CefTask*>(wParam);
	if (task.get())
	{
		task->Execute();
		task->Release();
	}
	return TRUE;
}

